import axios from "axios";
import { ElMessage } from "element-plus";
import { ResponseCodeEnum } from "./enums";

// 构造基本请求 (注意: SSE 请求不走这里)
const myAxios = axios.create({
  baseURL: "http://charles.wow.sh.cn",         // 请求发送目标
  timeout: 10000,                           // 请求超时时间
  withCredentials: true,                    // 表示 axios 请求会携带 cookie, 重要!
});

// 全局请求拦截器
myAxios.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// 全局响应拦截器
myAxios.interceptors.response.use(
  function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    const { data } = response;

    /**
     * 权限校验 (后端)
     */
    if (data.code === ResponseCodeEnum.NOT_LOGIN_ERROR) {
      // 不是获取用户信息的请求，并且用户目前不是已经在用户登录页面，则跳转到登录页面
      if (
        !response.request.responseURL.includes("/user/login_user") &&
        !window.location.pathname.includes("/user/login")
      ) {
        // ElMessage.error("未登录, 请先登录");
        window.location.href = `/user/login`;
      }
    }

    return response;
  },
  function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  }
);

export default myAxios;
